package com.shoulder.launcher.listener;

import com.shoulder.core.utils.LogTraceUtils;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 配置请求的监听器
 * todo 还有好多事情要想
 * todo 20240207: 这里要注意,如果在请求内部再次调用http直接调用其他接口，链路id会发生变化
 * todo 当然，这种情况很少而且可以忽略
 */
@Slf4j
public class LauncherRequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String requestURI = request.getRequestURI();
        log.info("监听到请求 {} 完成 {}", requestURI, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        LogTraceUtils.remove();
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String requestURI = request.getRequestURI();
        String traceId = request.getHeader(LogTraceUtils.TRACE_ID);
        //如果有上层调用就用上层的ID
        if (traceId == null) {
            LogTraceUtils.set();
        } else {
            LogTraceUtils.set(traceId);
        }
        log.info("监听到请求 {} 到来 {}", requestURI, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }
}
